AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

local Ground = 1 + 0 + 2 + 8 + 32
local Pressure_Increment = 80
local Energy_Increment = 10

function ENT:Initialize()
	self.Entity:SetModel( "models/props_junk/terracotta01.mdl" )
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	self.Entity:SetColor( 64, 64, 255, 255 )

	local phys = self.Entity:GetPhysicsObject()
	self.val1 = 0
	self.valgen = 0
	self.overdrive = 0
	self.lastused = 0
	
	self.timer = CurTime() +  1
	if (phys:IsValid()) then
		phys:Wake()
		phys:SetMass(50)
	end

	LS_RegisterEnt(self.Entity)
	RD_AddResource(self.Entity, "water", 0)

	self.Outputs = Wire_CreateOutputs(self.Entity, { "Generation" })
end

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end

	local SpawnPos = tr.HitPos + tr.HitNormal * 75

	local ent = ents.Create( "moisture_scoop" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:Setup()
end

function ENT:OnRemove()
	Dev_Unlink_All(self.Entity)
end


function ENT:Use()
end

function ENT:Output()
	return 1
end

function ENT:Collect_Water()
	local divider = 0
	if (self.environment.inwater == 1) then
		divider = 4
	else
		divider = 16
	end
	local vel = self.Entity:WorldToLocal(self.Entity:GetVelocity()+self.Entity:GetPos())
	local speed = vel.z
	local square = false
	if (speed < 0) then speed = 0 end --make sure its not moving backwards
	local water = math.Round(speed/divider)
	if (speed > 250) then 
		speed = speed - 250
		square = true
	end
	local water = math.Round(speed/divider)
	self.valgen = water
	if square then
		water = water + math.Round(math.sqrt(speed))
	end
	if (water > 10) then water = 10 end --maximum
	RD_SupplyResource(self, "water", water)
	self.val1 = speed
	return
end

function ENT:Think()
	if ( self.timer > CurTime() ) then return end
	self:Collect_Water()
	self.timer = CurTime() +  1
	self:SetOverlayText("Water Moisture Scoop\nGeneration: ".. self.valgen)
	Wire_TriggerOutput(self.Entity, "Generation", self.valgen)
end


function ENT:AcceptInput(name,activator,caller)
end

function ENT:PreEntityCopy()
	RD_BuildDupeInfo(self.Entity)
	if (WireAddon == 1) then
		local DupeInfo = Wire_BuildDupeInfo(self.Entity)
		if DupeInfo then
			duplicator.StoreEntityModifier( self.Entity, "WireDupeInfo", DupeInfo )
		end
	end
end

function ENT:PostEntityPaste( Player, Ent, CreatedEntities )
	RD_ApplyDupeInfo(Ent, CreatedEntities)
	if (WireAddon == 1) then
		if (Ent.EntityMods) and (Ent.EntityMods.WireDupeInfo) then
			Wire_ApplyDupeInfo(Player, Ent, Ent.EntityMods.WireDupeInfo, function(id) return CreatedEntities[id] end)
		end
	end
end
